require(["config"],function(){
	require(["jquery","template","header","zoom","fly","cookie","carousel"],function($,template){
		function Detail(){
			this.render();
		}
		
		Detail.prototype = {
			constructor:Detail,
			//渲染详情页面数据
			render:function(){
				$.ajax("http://rap2api.taobao.org/app/mock/86513/api/detail")
					.done($.proxy(this.handleDate,this));
			},
			handleDate: function(data){
				//获取使用数据
				data = data.res_body.data;
				//渲染
				var html = template("detail_template",data);
				$(".content_box").prepend(html);
				//放大镜
				this.zoom();
				//注册事件监听
				this.addListener();
				//加载轮播图
				this.loadCarousel();
			},
			//轮播图
			loadCarousel: function(){
				$(".carousel-box").carousel({
					imgs:[
						{href:"#",src:"/images/m1.jpg"},
						{href:"#",src:"/images/m2.jpg"},
						{href:"#",src:"/images/m3.jpg"},
						{href:"#",src:"/images/m4.jpg"},
						{href:"#",src:"/images/m5.jpg"},
					],
					width:227,
					height:305,
					duration: 3000
				});
			},
			//放大镜
			zoom: function(){
				$(".middle-zoom").elevateZoom({
					gallery:'gal1', 
					cursor: 'pointer', 
					galleryActiveClass: 'active'
				});
			},
			addListener: function() {
				// 添加到购物车
				$(".btn-buy").click(this.addCartHander);
			},
			addCartHander:function(event){
				
					//获取当前选购商品的信息
					var currentProduct = {
						id:$(".prod_id").text(),
						title:$(".prod_title").text(),
						img:$("#gal1 img:first").attr("src"),
						price:$(".prod_id").text(),
						amount:1
					};
					console.log(currentProduct);
					//从cookie中读取数据
					$.cookie.json =true;
					var products =  $.cookie("products") || [];
					//判断是否已有选购
					var has = products.some(function(prod){
						if(prod.id == currentProduct.id){
							prod.amount++;
							return true;
						}
						return false;
					});
					if(!has)//未选购
					products.push(currentProduct);
					$.cookie("products",products,{expires:10,path:"/"});
					
					
					//抛物线效果
					var end = $(".bag_left").offset();
						end.top -= $(window).scrollTop();
					var	start = {top:event.pageY-$(window).scrollTop(),left:event.pageX};//起点
					var flyer = $("#gal1 img:first").clone();
					//运动
					flyer.fly({
						start,
						end,
						onEnd:function(){
							this.destroy();
						}
					});
					
					return false;//阻止冒泡和阻止默认
				
			}
		}
		
		new Detail();
	});
});
